//
//  GoodsDetailViewController.m
//  XDCommonApp
//
//  Created by xindao on 14-7-1.
//  Copyright (c) 2014年 XD-XY. All rights reserved.
//



#import "GoodsDetailViewController.h"
#import "UIImageView+WebCache.h"
@interface GoodsDetailViewController ()

@end

@implementation GoodsDetailViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)backPrePage{
    [headerView free];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    dataArray = [[NSMutableArray alloc] init];

    backScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, UI_MAINSCREEN_HEIGHT - UI_NAVIGATION_BAR_HEIGHT)];
    backScrollView.delegate = self;
//    backScrollView.contentSize = CGSizeMake(UI_SCREEN_WIDTH, 515);
    backScrollView.pagingEnabled = NO;
    [self.contentView addSubview:backScrollView];

    headerView = [MJRefreshHeaderView header];
    headerView.scrollView = backScrollView;
    headerView.delegate = self;

    [self initViews];
    [self getData];
}

- (void)initViews{
    int height = 0;
    if (IOS7) {
        height = 20;
    }

    UIImageView * shareIV = [[UIImageView alloc] initWithFrame:CGRectMake(285, height+10, 25, 25)];
    shareIV.image = [UIImage imageNamed:@"shareBtn_img"];
    [self.navigationBarView addSubview:shareIV];

    [XDTools getAButtonForView:self.navigationBarView frame:CGRectMake(270, height, 50, 44) nomalTitle:nil hlTitle:nil titleColor:nil bgColor:[UIColor clearColor] nbgImage:nil hbgImage:nil action:@selector(shareBtnClick) target:self buttonTpye:UIButtonTypeCustom];
    
    self.shareView = [[XDShareView alloc]initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, UI_SCREEN_HEIGHT)];
    _shareView.delegate = self;
    [self.view addSubview:_shareView];

    headIV = [[UIImageView alloc] initWithFrame:CGRectMake(13, 25, 80, 80)];
    [backScrollView addSubview:headIV];

    nameLB = [XDTools addAlabelForAView:backScrollView withText:nil frame:CGRectMake(100, 26, 143, 26) font:[UIFont systemFontOfSize:17] textColor:RGBA(68, 68, 68, 1)];

    subTitleLB = [XDTools addAlabelForAView:backScrollView withText:nil frame:CGRectMake(100, 53, 186, 40) font:[UIFont systemFontOfSize:15] textColor:RGBA(129, 129, 129, 1)];

    UIImageView * lineIV1 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 137, 320, .5f)];
    lineIV1.image = [UIImage imageNamed:@"line"];
    [backScrollView addSubview:lineIV1];

    [XDTools addAlabelForAView:backScrollView withText:@"软件介绍" frame:CGRectMake(17,160,75,20) font:[UIFont systemFontOfSize:17] textColor:RGBA(68, 68, 68, 1)];

    contentLB = [XDTools addAlabelForAView:backScrollView withText:nil frame:CGRectMake(17,190,295,80) font:[UIFont systemFontOfSize:15] textColor:RGBA(129, 129, 129, 1)];

    lineIV2 = [[UIImageView alloc] initWithFrame:CGRectMake(0, height_y(contentLB)+20, 320, .5f)];
    lineIV2.image = [UIImage imageNamed:@"line"];
    [backScrollView addSubview:lineIV2];

    howToUseLB = [XDTools addAlabelForAView:backScrollView withText:@"应用截图" frame:CGRectMake(17,height_y(contentLB)+40,75,20) font:[UIFont systemFontOfSize:17] textColor:RGBA(68, 68, 68, 1)];

    picScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, height_y(contentLB)+80, 320, 298)];
    picScrollView.delegate = self;
    [backScrollView addSubview:picScrollView];

    payBtn =creatXRButton(CGRectMake(15, height_y(picScrollView) + 50, UI_SCREEN_WIDTH -30, 44),@"去体验",nil,nil);
    [payBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [payBtn setBackgroundColor:RGBA(241, 141, 0, 1)];
    [payBtn addTarget:self action:@selector(goToOtherPlace) forControlEvents:UIControlEventTouchUpInside];
    payBtn.layer.masksToBounds = YES;
    payBtn.layer.cornerRadius = 3;
    [backScrollView addSubview:payBtn];


}

- (void)getData{

    if ([XDTools NetworkReachable])
    {
        NSDictionary * dic = @{@"goods_id": _goodsID};


        NSMutableDictionary *muDict = [[NSMutableDictionary alloc] initWithDictionary:dic];
        NSMutableString *params = [[NSMutableString alloc] init];
        for (id keys in muDict) {
            [params appendFormat:@"&%@=%@",keys,[muDict objectForKey:keys]];
        }
        //        NSRange rang = [params rangeOfString:@"?"];
        //        if(rang.location == NSNotFound){
        //            NSRange rangAnd = [params rangeOfString:@"&"];
        //            [params replaceCharactersInRange:rangAnd withString:@"?"];
        //        }

        NSString *urlStr = [NSString stringWithFormat:@"http://www.xindaoapp.com/maodai/plugins/API.v1.0/?&a=category&m=activityshow%@",params];
        urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        DDLOG(@"urlStr:%@", urlStr);
        NSURL *url = [NSURL URLWithString:urlStr];
        ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
        [request setTimeOutSeconds:12];



        __weak ASIHTTPRequest * mrequest = request;
        [request setCompletionBlock:^{

            [XDTools hideProgress:self.view];

            NSDictionary *tempDic = [XDTools  JSonFromString:[mrequest responseString]];

            if ([[tempDic objectForKey:@"result"] intValue] == 1)
            {
                [headIV setImageWithURL:tempDic[@"data"][@"goods_thumb"] placeholderImage:nil];
                nameLB.text = tempDic[@"data"][@"goods_name"];
                self.titleLabel.text = nameLB.text;

                subTitleLB.text = tempDic[@"data"][@"goods_brief"];
                [subTitleLB sizeToFit];
                if (subTitleLB.frame.size.height > 40) {
                    subTitleLB.frame = CGRectMake(100, 53, 186, 41);
                }

                contentLB.text = tempDic[@"data"][@"goods_desc"];
                [contentLB sizeToFit];

                lineIV2.frame = CGRectMake(0, height_y(contentLB)+20, 320, .5f);
                howToUseLB.frame = CGRectMake(17,height_y(contentLB)+40,75,20);
                picScrollView.frame = CGRectMake(0, height_y(contentLB)+80, 320, 298);
//                payBtn.frame = CGRectMake(15, height_y(picScrollView)+40, UI_SCREEN_WIDTH -30, 44);
                [payBtn setFrame:CGRectMake(15, height_y(picScrollView) + 50, UI_SCREEN_WIDTH -30, 44)];
                NSArray * imageArray = tempDic[@"data"][@"img_url"];
                for (int i = 0; i < imageArray.count; i++) {
                    UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(5+185*i, 0, 355/2.0f, 295)];
                    [imageView setImageWithURL:[NSURL URLWithString:imageArray[i]] placeholderImage:nil];
                    [picScrollView addSubview:imageView];
                }
                picScrollView.contentSize = CGSizeMake(10 + 185*imageArray.count,295);

                backScrollView.contentSize = CGSizeMake(320, height_y(picScrollView) + 120);

                [headerView endRefreshing];
            }
            else
            {
                [XDTools showTips:[tempDic objectForKey:@"msg"] toView:self.view];
                [headerView endRefreshing];
            }
        }];

        [request setFailedBlock:^{
            [XDTools hideProgress:self.view];
            [headerView endRefreshing];
            NSError *error = [mrequest error];
            DDLOG_CURRENT_METHOD;
            DDLOG(@"error=%@",error);
            if (mrequest.error.code == 2) {
                [XDTools showTips:@"网络请求超时" toView:self.view];
            }
        }];
        if (!notFirst) {
            [XDTools showProgress:self.view];
            notFirst = YES;
        }
        [request startAsynchronous];
        
    }
    else
    {
        [XDTools showTips:brokenNetwork toView:self.view];
        [headerView endRefreshing];
    }
}

- (void)goToOtherPlace{
    UIApplication *app = [UIApplication sharedApplication];

    NSURL *url = [NSURL URLWithString:@"test://com.a.test"];
    NSURL * webUrl = [NSURL URLWithString:@"http://www.baidu.com"];
    if ([app canOpenURL:url]) {

        [app openURL:url];

    }else {

        [app openURL:webUrl];
    }

}

#pragma mark - MJRefreshView Delegate
- (void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView{
    if (refreshView == headerView) {
        [NSTimer scheduledTimerWithTimeInterval:0.4 target:self selector:@selector(getNewData) userInfo:nil repeats:NO];
    }
}

- (void)getNewData{

    [self getData];
    
}

#pragma mark ================分享按钮点击===================
-(void)shareBtnClick
{
    [_shareView setViewShow];
    DDLOG_CURRENT_METHOD;
}

#pragma mark ===============xdshareview delegate==========
-(void)shareViewBtnCLick:(UIButton *)button
{
    if (button.tag == 1001){
        [[UMSocialControllerService defaultControllerService] setShareText:@"我刚刚使用“喵贷”，得到了我朝思暮想的ta！你也一起来试试吧！喵贷，青春专属信贷应用，一次购物分期支付，无需抵押，不用证明，只要拿出诚意、亮出诚信，你和你的梦想只有一个app的距离！点击链接极速下载：" shareImage:[UIImage imageNamed:@"Icon"] socialUIDelegate:self];
         [UMSocialData defaultData].extConfig.title = @"喵贷信用支付";
        [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToSina].snsClickHandler(self,[UMSocialControllerService defaultControllerService],YES);
    }else{
        //朋友圈分享
        [[UMSocialControllerService defaultControllerService] setShareText:@"我刚刚使用“喵贷”，得到了我朝思暮想的ta！你也一起来试试吧！喵贷，青春专属信贷应用，一次购物分期支付，无需抵押，不用证明，只要拿出诚意、亮出诚信，你和你的梦想只有一个app的距离！点击链接极速下载：" shareImage:[UIImage imageNamed:@"Icon"] socialUIDelegate:self];
        [UMSocialData defaultData].extConfig.title = @"喵贷信用支付";
        [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToWechatTimeline].snsClickHandler(self,[UMSocialControllerService defaultControllerService],YES);
    }
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
